package async;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author fei.fang
 * @date 2021/8/27
 **/
public class CyclicBarrierTest {

    public static class Soilder implements Runnable {

        private String soilderName;

        private final CyclicBarrier cyclicBarrier;

        public Soilder(String soilderName, CyclicBarrier cyclicBarrier) {
            this.soilderName = soilderName;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                System.out.println(soilderName + "准备");
                cyclicBarrier.await();

                dowork();
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

        private void dowork(){
            try {
                Thread.sleep(Math.abs(new Random().nextInt(8)) * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(soilderName + "任务完成");
        }
    }

    public static class BarrierRun implements Runnable {
        private boolean flag;

        private int num;

        public BarrierRun(boolean flag, int num) {
            this.flag = flag;
            this.num = num;
        }

        @Override
        public void run() {
            if (flag) {
                System.out.println("士兵" + num + "个,任务完成");
            }else{
                System.out.println("士兵" + num + "个，集合完成");
                flag = true;
            }
        }
    }

    public static void main(String[] args) {
        final int n = 10;

        CyclicBarrier cyclicBarrier = new CyclicBarrier(n, new BarrierRun(false, n));

        System.out.println("集合队伍");

        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i = 0; i < n; i++) {
            System.out.println("士兵" + i + "报道");
            exec.execute(new Soilder("士兵" + i, cyclicBarrier));
        }
    }

}
